import { ref, computed } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { getUserCoupons, getCouponsByStatus, redeemCoupon } from '@/api/coupon';
import { CouponStatus, type Coupon } from '@/types/coupon';

/**
 * 优惠券业务逻辑
 * 职责:优惠券的状态管理和业务处理
 */
export function useCoupon() {
  const userStore = useUserStore();
  
  const coupons = ref<Coupon[]>([]);
  const loading = ref(false);
  const currentTab = ref(0); // 0:未使用, 1:已使用, 2:已过期

  // 加载优惠券列表
  const loadCoupons = async (status?: number) => {
    if (!userStore.userInfo?.customerId) return;

    try {
      loading.value = true;
      
      let data: Coupon[];
      if (status !== undefined) {
        data = await getCouponsByStatus(userStore.userInfo.customerId, status);
      } else {
        data = await getUserCoupons(userStore.userInfo.customerId);
      }
      
      coupons.value = Array.isArray(data) ? data : [];
    } catch (error) {
      console.error('加载优惠券失败:', error);
      coupons.value = [];
    } finally {
      loading.value = false;
    }
  };

  // 根据tab过滤优惠券
  const filteredCoupons = computed(() => {
    if (currentTab.value === 0) {
      return coupons.value.filter(c => c.status === CouponStatus.UNUSED);
    } else if (currentTab.value === 1) {
      return coupons.value.filter(c => c.status === CouponStatus.USED);
    } else if (currentTab.value === 2) {
      return coupons.value.filter(c => c.status === CouponStatus.EXPIRED);
    }
    return coupons.value;
  });

  // 统计各状态优惠券数量
  const stats = computed(() => {
    return {
      unused: coupons.value.filter(c => c.status === CouponStatus.UNUSED).length,
      used: coupons.value.filter(c => c.status === CouponStatus.USED).length,
      expired: coupons.value.filter(c => c.status === CouponStatus.EXPIRED).length,
    };
  });

  // 兑换优惠券
  const handleRedeem = async (code: string) => {
    if (!userStore.userInfo?.customerId) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return false;
    }

    try {
      uni.showLoading({ title: '兑换中...' });
      
      await redeemCoupon(userStore.userInfo.customerId, {
        exchangeCode: code
      });
      
      uni.hideLoading();
      uni.showToast({
        title: '兑换成功',
        icon: 'success'
      });

      // 刷新列表
      await loadCoupons();
      
      return true;
    } catch (error: any) {
      uni.hideLoading();
      console.error('兑换失败:', error);
      uni.showToast({
        title: error.message || '兑换失败',
        icon: 'none'
      });
      return false;
    }
  };

  // 格式化优惠券金额显示
  const formatCouponAmount = (coupon: Coupon): string => {
    if (coupon.couponType === 1) { // 现金券
      return `¥${coupon.discountAmount || 0}`;
    } else if (coupon.couponType === 2) { // 折扣券
      return `${(coupon.discountRate || 10) / 10}折`;
    }
    return '礼品券';
  };

  // 格式化使用条件
  const formatCondition = (coupon: Coupon): string => {
    if (coupon.minOrderAmount > 0) {
      return `满${coupon.minOrderAmount}元使用`;
    }
    return '无门槛';
  };

  return {
    coupons,
    filteredCoupons,
    stats,
    loading,
    currentTab,
    loadCoupons,
    handleRedeem,
    formatCouponAmount,
    formatCondition
  };
}